const express = require('express')
const Ctrl = require("../controller/Article")
const Schema = require("../schema/Article")
const {validate} = require("express-validation")
const multer = require('multer')
const path = require('path')
const fs = require('fs')
// 创建 multer 实例对象, 通过 dest 属性指定文件存放路径

//上传的文件保存在 upload
const storage = multer.diskStorage({
    //存储的位置
    destination(req, file, cb) {
        fs.access(path.join(__dirname, "../uploads"), (err) => {
            if (err) {
                fs.mkdir(path.join(__dirname, "../uploads"), {recursive: true}, err => {
                    if (err) throw err;
                });
            }
            cb(null, path.join(__dirname, "../uploads"))
        })
    },
    //文件名字的确定 multer默认帮我们取一个没有扩展名的文件名，因此需要我们自己定义
    filename(req, file, cb) {
        cb(null, Date.now() + file.originalname)
    }
})
const upload = multer({storage})
const Router = express.Router()

Router.get("/api/article/", Ctrl.getAllArticles)
Router.get("/api/article/cate/:cate", Ctrl.getAllArticlesByCateId)
Router.get("/api/article/:a_id", Ctrl.getArticleById)

Router.post("/article/", upload.single('cover_img'), validate(Schema.addArticle), Ctrl.addArticle)


module.exports = Router